import axios from 'axios'
import type {
  ParseVideoRequest,
  BatchParseRequest,
  VideoInfo,
  PlatformInfo,
  HealthResponse,
  ServiceStats,
  ApiResponse
} from '@/types/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: '/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    console.log(`🚀 API请求: ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('❌ 请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    console.log(`✅ API响应: ${response.config.url} - ${response.status}`)
    return response
  },
  (error) => {
    console.error('❌ 响应错误:', error.response?.data || error.message)
    return Promise.reject(error)
  }
)

export class VideoAPI {
  /**
   * 解析单个视频
   */
  static async parseVideo(data: ParseVideoRequest): Promise<VideoInfo> {
    try {
      const response = await apiClient.post('/parse/video', data)
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || error.message || '视频解析失败')
    }
  }

  /**
   * 批量解析视频
   */
  static async parseBatch(data: BatchParseRequest): Promise<VideoInfo[]> {
    try {
      const response = await apiClient.post('/parse/batch', data)
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || error.message || '批量解析失败')
    }
  }

  /**
   * 获取支持的平台列表
   */
  static async getSupportedPlatforms(): Promise<PlatformInfo[]> {
    try {
      const response = await apiClient.get('/platforms')
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || error.message || '获取平台列表失败')
    }
  }

  /**
   * 健康检查
   */
  static async healthCheck(): Promise<HealthResponse> {
    try {
      const response = await apiClient.get('/health')
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || error.message || '健康检查失败')
    }
  }

  /**
   * 获取服务统计
   */
  static async getStats(): Promise<ServiceStats> {
    try {
      const response = await apiClient.get('/stats')
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.detail || error.message || '获取统计信息失败')
    }
  }
}

// 工具函数：验证URL格式
export function validateUrl(url: string): boolean {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

// 工具函数：检测平台类型
export function detectPlatform(url: string): string {
  const platformPatterns = {
    douyin: [/douyin\.com/, /iesdouyin\.com/, /dy\.app/],
    tiktok: [/tiktok\.com/, /vm\.tiktok\.com/, /vt\.tiktok\.com/],
    bilibili: [/bilibili\.com/, /b23\.tv/, /bili\.li/]
  }

  for (const [platform, patterns] of Object.entries(platformPatterns)) {
    if (patterns.some(pattern => pattern.test(url))) {
      return platform
    }
  }

  return 'auto'
}

